import axios, { AxiosError } from 'axios';
import type { ApiResponse } from '@/types';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3301/api';

// Create axios instance
export const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - add auth token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('access_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor - handle errors
api.interceptors.response.use(
  (response) => response,
  (error: AxiosError<any>) => {
    if (error.response?.status === 401) {
      // Unauthorized - redirect to login
      localStorage.removeItem('access_token');
      window.location.href = '/login';
    }
    
    // FastAPI返回的错误在detail字段�?
    const message = error.response?.data?.detail || error.response?.data?.message || '请求失败';
    return Promise.reject(new Error(message));
  }
);

// Auth API
export const authApi = {
  login: async (username: string, password: string) => {
    const params = new URLSearchParams();
    params.append('username', username);
    params.append('password', password);
    
    const response = await api.post<{ access_token: string; token_type: string }>(
      '/auth/login',
      params,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );
    return response.data;
  },

  logout: async () => {
    localStorage.removeItem('access_token');
  },

  getCurrentUser: async () => {
    const response = await api.get('/auth/me');
    return response.data;
  },
};

// Documents API
export const documentsApi = {
  list: async (params?: { 
    page?: number; 
    page_size?: number; 
    search?: string;
    category_id?: string;
    knowledge_base_id?: string;
    status?: string;
  }) => {
    const response = await api.get('/documents/list', { params });
    return response.data;
  },

  get: async (id: string) => {
    const response = await api.get(`/documents/${id}`);
    return response.data;
  },

  upload: async (file: File, metadata?: { 
    title?: string;
    category_id?: string; 
    knowledge_base_id?: string;
    tags?: string[];
  }) => {
    const formData = new FormData();
    formData.append('file', file);
    if (metadata?.title) {
      formData.append('title', metadata.title);
    }
    if (metadata?.category_id) {
      formData.append('category_id', metadata.category_id);
    }
    if (metadata?.knowledge_base_id) {
      formData.append('knowledge_base_id', metadata.knowledge_base_id);
    }
    if (metadata?.tags) {
      formData.append('tags', JSON.stringify(metadata.tags));
    }

    const response = await api.post('/documents/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  },

  update: async (id: string, data: {
    title?: string;
    category_id?: string;
    knowledge_base_id?: string;
    tags?: string[];
    summary?: string;
  }) => {
    const response = await api.put(`/documents/${id}`, data);
    return response.data;
  },

  delete: async (id: string) => {
    const response = await api.delete(`/documents/${id}`);
    return response.data;
  },

  vectorize: async (id: string) => {
    const response = await api.post(`/documents/${id}/vectorize`, {}, {
      timeout: 180000, // 3分钟超时，向量化可能需要较长时间
    });
    return response.data;
  },

  download: async (id: string, filename: string) => {
    const response = await api.get(`/documents/${id}/download`, {
      responseType: 'blob',
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
  },

  // AI智能分类
  autoClassify: async (documentId: string, modelName?: string) => {
    const response = await api.post(`/documents/${documentId}/auto-classify`, null, {
      params: { model_name: modelName }
    });
    return response.data;
  },

  applyClassification: async (documentId: string, categoryId: string) => {
    const response = await api.post(`/documents/${documentId}/apply-classification`, null, {
      params: { category_id: categoryId }
    });
    return response.data;
  },

  batchClassify: async (documentIds: string[], modelName?: string) => {
    const response = await api.post('/documents/batch-classify', {
      document_ids: documentIds,
      model_name: modelName
    });
    return response.data;
  },

  // 批量删除文档
  batchDelete: async (documentIds: string[]) => {
    const response = await api.post('/documents/batch-delete', documentIds);
    return response.data;
  },

  // 批量向量化文档（限制最多5个）
  batchVectorize: async (documentIds: string[]) => {
    const response = await api.post('/documents/batch-vectorize', documentIds);
    return response.data;
  },

  // 批量移动文档到其他知识库
  batchMove: async (documentIds: string[], targetKbId: string) => {
    const response = await api.post('/documents/batch-move', {
      document_ids: documentIds,
      target_kb_id: targetKbId
    });
    return response.data;
  },
};

// Shares API
export const sharesApi = {
  create: async (data: {
    document_id: string;
    shared_to_id: string;
    permission?: string;
    expires_at?: string;
  }) => {
    const response = await api.post('/shares/', data);
    return response.data;
  },

  getReceived: async () => {
    const response = await api.get('/shares/received');
    return response.data;
  },

  getByDocument: async (documentId: string) => {
    const response = await api.get(`/shares/by-document/${documentId}`);
    return response.data;
  },

  delete: async (shareId: string) => {
    const response = await api.delete(`/shares/${shareId}`);
    return response.data;
  },
};

// Categories API
export const categoriesApi = {
  list: async (tree: boolean = false) => {
    const response = await api.get('/categories/list', { params: { tree } });
    return response.data;
  },

  get: async (id: string) => {
    const response = await api.get(`/categories/${id}`);
    return response.data;
  },

  create: async (data: { 
    name: string; 
    description?: string; 
    icon?: string;
    color?: string;
    parent_id?: string;
    sort_order?: number;
  }) => {
    const response = await api.post('/categories/create', data);
    return response.data;
  },

  update: async (id: string, data: {
    name?: string;
    description?: string;
    icon?: string;
    color?: string;
    parent_id?: string;
    sort_order?: number;
  }) => {
    const response = await api.put(`/categories/${id}`, data);
    return response.data;
  },

  delete: async (id: string) => {
    const response = await api.delete(`/categories/${id}`);
    return response.data;
  },
};

// Knowledge Base API
export const knowledgeBaseApi = {
  list: async () => {
    const response = await api.get('/knowledge-bases/list');
    return response.data;
  },

  create: async (data: { name: string; description?: string; visibility: string }) => {
    const response = await api.post('/knowledge-bases/create', data);
    return response.data;
  },

  update: async (id: string, data: { name?: string; description?: string; visibility?: string }) => {
    const response = await api.put(`/knowledge-bases/${id}`, data);
    return response.data;
  },

  delete: async (id: string) => {
    const response = await api.delete(`/knowledge-bases/${id}`);
    return response.data;
  },
};

// 兼容旧代码的导出别名
export const knowledgeBasesApi = knowledgeBaseApi;

// Chat API
export const chatApi = {
  getSessions: async () => {
    const response = await api.get('/chat/sessions');
    return response.data;
  },

  createSession: async (data: { title: string; knowledge_base_id?: string }) => {
    const response = await api.post('/chat/sessions', data);
    return response.data;
  },

  deleteSession: async (sessionId: string) => {
    const response = await api.delete(`/chat/sessions/${sessionId}`);
    return response.data;
  },

  getSessionMessages: async (sessionId: string) => {
    const response = await api.get(`/chat/sessions/${sessionId}/messages`);
    return response.data;
  },

  sendMessage: async (
    message: string, 
    options?: {
      session_id?: string;
      knowledge_base_id?: string;
      temperature?: number;
      max_tokens?: number;
      stream?: boolean;
    }
  ) => {
    const response = await api.post('/chat/', {
      message,
      session_id: options?.session_id,
      knowledge_base_id: options?.knowledge_base_id,
      temperature: options?.temperature || 0.7,
      max_tokens: options?.max_tokens || 2000,
      stream: options?.stream || false,
    });
    return response.data;
  },

  sendMessageStream: async (
    message: string,
    onChunk: (chunk: string) => void,
    onDone: (sessionId?: string) => void,
    onError: (error: string) => void,
    options?: {
      session_id?: string;
      knowledge_base_id?: string;
      document_ids?: string;
      temperature?: number;
      max_tokens?: number;
      onSources?: (sources: any[]) => void;
    }
  ) => {
    const token = localStorage.getItem('access_token');

    // 使用fetch进行流式请求
    const response = await fetch(`${API_BASE_URL}/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        message,
        session_id: options?.session_id,
        knowledge_base_id: options?.knowledge_base_id,
        document_ids: options?.document_ids,
        temperature: options?.temperature || 0.7,
        max_tokens: options?.max_tokens || 2000,
        stream: true,
      })
    });

    if (!response.ok) {
      onError(`请求失败: ${response.status}`);
      return;
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      onError('无法读取响应流');
      return;
    }

    try {
      let buffer = '';
      let sessionId: string | undefined;
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        // 解码并添加到buffer
        buffer += decoder.decode(value, { stream: true });
        
        // 按行分割
        const lines = buffer.split('\n');
        
        // 保留最后一个不完整的行
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonStr = line.slice(6).trim();
              if (jsonStr) {
                const data = JSON.parse(jsonStr);
                if (data.type === 'session_id') {
                  sessionId = data.session_id;
                } else if (data.type === 'content') {
                  onChunk(data.content);
                } else if (data.type === 'sources') {
                  if (options?.onSources && data.sources) {
                    options.onSources(data.sources);
                  }
                } else if (data.type === 'done') {
                  onDone(sessionId);
                  return;
                } else if (data.type === 'error') {
                  onError(data.message);
                  return;
                }
              }
            } catch (e) {
              console.error('解析JSON失败:', line, e);
            }
          }
        }
      }
      
      // 处理剩余的buffer
      if (buffer.trim()) {
        if (buffer.startsWith('data: ')) {
          try {
            const jsonStr = buffer.slice(6).trim();
            if (jsonStr) {
              const data = JSON.parse(jsonStr);
              if (data.type === 'done') {
                onDone();
              }
            }
          } catch (e) {
            console.error('解析最后JSON失败:', buffer, e);
          }
        }
      }
    } catch (error: any) {
      console.error('流式读取错误:', error);
      onError(error.message || '未知错误');
    }
  },

  checkHealth: async () => {
    const response = await api.get('/chat/health');
    return response.data;
  },
};

// Ollama Models API
export const modelsApi = {
  list: async () => {
    const response = await api.get('/models/ollama/list');
    return response.data;
  },

  testConnection: async () => {
    const response = await api.get('/models/ollama/test');
    return response.data;
  },

  getConfig: async () => {
    const response = await api.get('/models/config');
    return response.data;
  },

  updateConfig: async (config: {
    llm_model: string;
    embedding_model: string;
    ollama_base_url?: string;
    temperature?: number;
    max_tokens?: number;
  }) => {
    const response = await api.post('/models/config', config);
    return response.data;
  },
};

// 统计API
export const statsApi = {
  getDashboard: async () => {
    const response = await api.get('/stats/dashboard');
    return response.data;
  }
};

// Notes API
export const notesApi = {
  // 获取笔记列表
  list: async (params?: {
    search?: string;
    knowledge_base_id?: string;
    skip?: number;
    limit?: number;
  }) => {
    const response = await api.get('/notes/', { params });
    return response.data;
  },

  // 获取笔记详情
  get: async (id: string) => {
    const response = await api.get(`/notes/${id}`);
    return response.data;
  },

  // 创建笔记
  create: async (data: {
    title: string;
    content: string;
    document_ids?: string[];
    knowledge_base_id?: string;
    metadata?: any;
  }) => {
    const response = await api.post('/notes/', data);
    return response.data;
  },

  // 更新笔记
  update: async (id: string, data: {
    title?: string;
    content?: string;
    document_ids?: string[];
    knowledge_base_id?: string;
  }) => {
    const response = await api.put(`/notes/${id}`, data);
    return response.data;
  },

  // 删除笔记
  delete: async (id: string) => {
    const response = await api.delete(`/notes/${id}`);
    return response.data;
  },

  // 从RAG对话保存到笔记
  saveFromChat: async (data: {
    note_id?: string;
    title: string;
    content: string;
    document_ids?: string[];
    metadata?: any;
  }) => {
    const response = await api.post('/notes/save-from-chat', data);
    return response.data;
  },

  // 获取笔记历史版本
  getVersions: async (noteId: string) => {
    const response = await api.get(`/notes/${noteId}/versions`);
    return response.data;
  },

  // 恢复到指定版本
  restoreVersion: async (noteId: string, versionNumber: number) => {
    const response = await api.post(`/notes/${noteId}/restore/${versionNumber}`);
    return response.data;
  },

  // 向量化笔记（加入知识库）
  vectorize: async (noteId: string, knowledge_base_id: string) => {
    const response = await api.post(`/notes/${noteId}/vectorize`, {
      knowledge_base_id
    }, {
      timeout: 180000, // 3分钟超时
    });
    return response.data;
  },
};

export default api;


